package com.qf.springbootdemo03.controller;

import com.qf.springbootdemo03.entity.ResultVO;
import com.qf.springbootdemo03.util.JwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 测试Jwt
 * @author q
 * @version V1.0
 * @date 2021/11/27
 **/
@RestController
@RequestMapping("/jwt")
public class JwtController {

    /**
     * 登陆成功后，把jwt回传给客户端
     * @param username
     * @param password
     * @param response
     * @return
     */
    @PostMapping("/login")
    public ResultVO<String> login(String username, String password, HttpServletResponse response){
        try {
            if ("lisi".equals(username) && "123456".equals(password)){
                Map<String, Object> claims = new HashMap<>();
                claims.put(Claims.SUBJECT, username);
                claims.put(Claims.ID, "1001");
                String jwt = JwtUtil.createJwt(new HashMap<>(), claims, 7);
                //把jwt返回出去
                return ResultVO.ok("登陆成功", jwt);
            }
            return ResultVO.error("登陆失败");
        } catch (Exception e) {
            e.printStackTrace();
            return ResultVO.error(e.getMessage());
        }
    }

    @GetMapping("/list")
    public ResultVO<String> findAll(HttpServletRequest request){
        try {

            //拦截器
            String jwtToken = request.getHeader("token");
            Map<String, Object> map = JwtUtil.parseJwt(jwtToken);

            //认证通过。
            //业务代码
            //查询用户
            String users = "zhangsan,lisi,wangwu";

            return ResultVO.ok("查询成功", users);
        } catch (MalformedJwtException e) {
            return ResultVO.error("认证失败");
        } catch (ExpiredJwtException e) {
            return ResultVO.error("登录已过期，请重新登录");
        } catch (Exception e) {
            return ResultVO.error("查询出错了");
        }
    }

}
